package com.herui.iot.data.user.source;

import com.alibaba.fastjson.TypeReference;
import com.herui.sdyu_lib.http.callback.Callback;
import com.herui.sdyu_lib.utils.JsonUtils;
import com.herui.sdyu_lib.utils.StringUtils;
import com.herui.sport_care.config.CacheKeyConfig;
import com.herui.sport_care.data.BaseCallBack;
import com.herui.sport_care.data.BaseRepository;
import com.herui.sport_care.data.user.Gender;
import com.herui.sport_care.data.user.UserInfo;
import com.herui.sport_care.request.SportResponse;
import com.herui.sport_care.request.UserRequest;
import com.herui.sport_care.utils.StorageUtils;

import java.util.HashMap;
import java.util.Map;

import static com.herui.sport_care.config.ServerConfig.retrofitCall;

/**
 * Created by amanda.shan on 2021/9/30.
 */
public class UserRepository extends BaseRepository implements UserSource {

    private static UserRepository instance;

    public static UserRepository getInstance() {
        if (instance == null) {
            synchronized (UserRepository.class) {
                if (instance == null) {
                    instance = new UserRepository();
                }
            }
        }
        return instance;
    }

    private UserInfo userInfo;

    public void clearAll() {

    }

    @Override
    public void login(String account, String password, Callback.CommonCallback<UserInfo> callback) {


        Map<String, Object> map = new HashMap<>();
        map.put("account", account);
        map.put("password", password);
        retrofitCall.call(retrofitCall.conver(UserRequest.class).login(map),
                new BaseCallBack<UserInfo>(callback) {
                    @Override
                    public SportResponse<UserInfo> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<UserInfo>>() {
                                });
                    }

                    @Override
                    public void onResult(UserInfo userInfo) {
                        UserRepository.this.userInfo = userInfo;
                        StorageUtils.saveSharedPreference(CacheKeyConfig.TOKEN_KEY, userInfo.getToken());
                        StorageUtils.saveSharedPreference(CacheKeyConfig.USER_INFO_KEY,
                                JsonUtils.toJSONString(userInfo));
                    }
                });
    }

    @Override
    public String getToken() {
        return StorageUtils.getStringSP(CacheKeyConfig.TOKEN_KEY);
    }

    public UserInfo getUserInfo() {
        if (userInfo == null){
            String s = StorageUtils.getStringSP(CacheKeyConfig.USER_INFO_KEY);
            if (!StringUtils.isEmpty(s)){
                try {
                    userInfo = JsonUtils.parseObject(s, UserInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

//        userInfo = new UserInfo();
//        userInfo.setId(26);
//        userInfo.setOrganId(1);

        return userInfo;
    }

    @Override
    public void verify(Callback.CommonCallback<String> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", getUserInfo().getId());
        map.put("token", getUserInfo().getToken());
        map.put("terminalType", "APP");
        retrofitCall.call(retrofitCall.conver(UserRequest.class).verify(map),
                new BaseCallBack<String>(callback) {
                    @Override
                    public SportResponse<String> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<String>>() {
                                });
                    }
                });
    }

    @Override
    public void modifyUserInfo(String name, String birthday, Gender gender, Callback.CommonCallback<String> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", getUserInfo().getId());
        if (!StringUtils.isEmpty(name)){
            map.put("name", name);
        }
        if (!StringUtils.isEmpty(birthday)){
            map.put("birthday", birthday);
        }
        if (gender != null){
            map.put("gender", gender);
        }
        retrofitCall.call(retrofitCall.conver(UserRequest.class).modifyUserInfo(map),
                new BaseCallBack<String>(callback) {
                    @Override
                    public SportResponse<String> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<String>>() {
                                });
                    }
                });
    }

    private Long sendTime;

    @Override
    public void getCode(String mobile, Callback.CommonCallback<String> callback) {
        if (sendTime != null && System.currentTimeMillis()-sendTime < 60*1000){
            callback.onError(null, "%s", "请稍后获取验证码");
            return;
        }
        sendTime = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("smsType", "CHANGE_MOBILE_PHONE");
        retrofitCall.call(retrofitCall.conver(UserRequest.class).getCode(map),
                new BaseCallBack<String>(callback) {
                    @Override
                    public SportResponse<String> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<String>>() {
                                });
                    }
                });
    }

    @Override
    public void modifyPhone(String mobile, String code,
                            Callback.CommonCallback<String> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", getUserInfo().getId());
        map.put("mobile", mobile);
        map.put("code", code);
        retrofitCall.call(retrofitCall.conver(UserRequest.class).modifyPhone(map),
                new BaseCallBack<String>(callback) {
                    @Override
                    public SportResponse<String> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<String>>() {
                                });
                    }
                });
    }

    @Override
    public void changePassword(String password, String formerPassword,
                               Callback.CommonCallback<String> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", getUserInfo().getId());
        map.put("password", password);
        map.put("formerPassword", formerPassword);
        retrofitCall.call(retrofitCall.conver(UserRequest.class).changePassword(map),
                new BaseCallBack<String>(callback) {
                    @Override
                    public SportResponse<String> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<String>>() {
                                });
                    }
                });
    }

    @Override
    public void loginOut(Callback.CommonCallback<String> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", getUserInfo().getId());
        map.put("terminalType", "APP");
        retrofitCall.call(retrofitCall.conver(UserRequest.class).loginOut(map),
                new BaseCallBack<String>(callback) {
                    @Override
                    public SportResponse<String> getApiResponse(String s) throws Exception {
                        return JsonUtils.parseObject(s,
                                new TypeReference<SportResponse<String>>() {
                                });
                    }
                });
        StorageUtils.remove(CacheKeyConfig.USER_INFO_KEY);
    }
}
